package com.cos.shop.web.controller;

import com.cos.shop.common.Const;
import com.cos.shop.common.ResponseResult;
import com.cos.shop.entity.Address;
import com.cos.shop.entity.User;
import com.cos.shop.services.AddressServices;
import com.cos.shop.services.impl.AddressServicesImpl;
import com.cos.shop.util.StringUtils;
import com.sun.org.apache.regexp.internal.REUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.rmi.server.UID;

/**
 * @author: COS
 * @time: 2023/5/11 15:22
 * @description:
 */
@WebServlet("/addr")
public class AddressController extends BaseServlet {
    private AddressServices as = new AddressServicesImpl();


    public String changeDefault(HttpServletRequest request, HttpServletResponse response) throws IOException {
        User user = (User) request.getSession().getAttribute(Const.LOGIN_INFO);
        int aid = StringUtils.stringToInt(request.getParameter("aid"));
        as.changeDefault(aid,user.getUid());
        // 直接重定向
        return Const.REDIRECT + "/addr?method=getAddress";
    }
    public String update(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int aid = StringUtils.stringToInt(request.getParameter("aid"));
        String aname = request.getParameter("aname");
        String aphone = request.getParameter("aphone");
        String adetail = request.getParameter("adetail");
        //封装数据
        Address a = new Address(aname,aphone,adetail,aid);
        //访问业务层
        as.updateAddress(a);
        // 直接重定向
        return Const.REDIRECT + "/addr?method=getAddress";
    }
    public String add(HttpServletRequest request, HttpServletResponse response) throws IOException {
        User user = (User) request.getSession().getAttribute(Const.LOGIN_INFO);
        String aname = request.getParameter("aname");
        String aphone = request.getParameter("aphone");
        String adetail = request.getParameter("adetail");
        //封装数据
        Address a = new Address(user.getUid(),aname,aphone,adetail);
        //访问业务层
        as.insertAddress(a);
        // 直接重定向
        return Const.REDIRECT + "/addr?method=getAddress";
    }

    public String delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int id = StringUtils.stringToInt(request.getParameter("id"));
        //访问业务层操作删除
        as.delete(id);
        // 直接重定向
        return Const.REDIRECT + "/addr?method=getAddress";
    }

    public String getAddress(HttpServletRequest request, HttpServletResponse response) {
        User user = (User) request.getSession().getAttribute(Const.LOGIN_INFO);
        //访问业务层
        ResponseResult all = as.getAll(user.getUid());
        request.setAttribute("rr", all);
        return Const.FORWARD + "self_info.jsp";
    }

}
